package 二叉树的递归遍历.前序遍历;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

public class Solution2 {
    public List<Integer> preorderTraversal(TreeNode root) {
        // 借用一个栈进行迭代递归
        Stack<TreeNode> stack = new Stack<>();
        List<Integer> list = new ArrayList<>();
        TreeNode p = root;
        while (p != null || !stack.isEmpty()) {
            if (p != null) {
                // p不为null，则遍历当前节点并移动指针到其左子树
                list.add(p.val);
                stack.push(p);
                p = p.left;
            } else {
                // p为null，则需要遍历当前null的父节点的右指针
                p = stack.pop();
                p = p.right;
            }
        }
        return list;
    }
}
